from django.contrib import messages
from django.shortcuts import get_object_or_404
from django.views.generic import TemplateView, ListView

from common.forms import SelectAssigneeForm
from common.mixins import UserCourseRelatedMixin, PageinatorMixin
from user.models import User
from course.models import Course
from course.views import SidebarMixin
from task.models import Task
from .forms import ResumeCommentForm, ResumeCreateForm
from .models import Resume
from user.forms import HorizontalFormHelper


class ResumeCtxComment(object):

    def __init__(self, t, a, f, dt):
        self.text = t
        self.author = a
        self.author_fullname = f
        self.time = dt
        self.collapsed = True


class ResumeCtxVersion(object):

    def __init__(self):
        self.id = 0
        self.comments = []
        self.url = ''
        self.has_comment = False
        self.last_updated_time = None
        self.comment_num = 0
        self.pk = ''
        self.can_comment = False

    def display_order(self):
        if len(self.comments) > 0:
            self.comments.sort(key=lambda x: x.time, reverse=True)
            self.last_updated_time = self.comments[0].time
            self.has_comment = True
            self.comments[0].collapsed = False
            self.comment_num = len(self.comments)


class ResumeCtxJob(object):

    def __init__(self):
        self.desc = ''
        self.versions = []
        self.last_updated_time = None

    def display_order(self):
        for v in self.versions:
            v.display_order()
        self.versions.sort(key=lambda x: x.last_updated_time, reverse=True)
        self.last_updated_time = self.versions[0].last_updated_time
        for i in range(len(self.versions)):
            self.versions[i].id = len(self.versions) - i
        self.versions[0].can_comment = True


class ResumeCtx(object):

    def __init__(self):
        self.jobs = {}
        self.ordered_jobs = []

    def display_order(self):
        for job in self.ordered_jobs:
            job.display_order()
        self.ordered_jobs.sort(key=lambda x: x.last_updated_time, reverse=True)


class ResumeCommentsView(UserCourseRelatedMixin,
                         SidebarMixin, TemplateView):

    template_name = 'resume/comments.html'
    section_title = 'Resume Comments'
    student = None
    form_helper = HorizontalFormHelper()
    task = None

    def get_resume_ctx(self, user):
        ctx = ResumeCtx()
        for resume in user.resumes.all():
            if resume.desc not in ctx.jobs:
                job = ResumeCtxJob()
                job.desc = resume.desc
                ctx.jobs[resume.desc] = len(ctx.ordered_jobs)
                ctx.ordered_jobs.append(job)
            # get the job object
            job = ctx.ordered_jobs[ctx.jobs[resume.desc]]
            # create a new version for this job
            version = ResumeCtxVersion()
            version.last_updated_time = resume.created_date
            version.url = resume.file.url
            version.pk = resume.pk
            # get all comments for that version
            for comment in resume.comments.all():
                author_id = comment.commenter.username
                author_fullname = (comment.commenter.last_name + ' ' +
                                   comment.commenter.first_name)
                cmt = ResumeCtxComment(comment.text, author_id,
                                       author_fullname, comment.created_date)
                version.comments.append(cmt)
            job.versions.append(version)
        ctx.display_order()
        return ctx

    def dispatch(self, request, student_id, course_id=None):
        self.student = User.objects.get(pk=student_id)
        self.course_id = course_id
        if course_id is None:
            self.course_slug = 1

        resume_id = request.GET.get('resume_id')
        if resume_id:
            resume = Resume.objects.get(id=resume_id)
            self.task = Task.objects.filter(
                ttype=Task.RESUME, assignee=request.user,
                resume=resume).first()

        return super(ResumeCommentsView, self).dispatch(
            request, student_id, course_id)

    def get(self, request, student_id, course_id):
        form = ResumeCommentForm()
        return self.render_to_response({
            'view': self,
            'form': form,
            'resume_ctx': self.get_resume_ctx(self.student)

        })

    def post(self, request, student_id, course_id):
        form = ResumeCommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.commenter = request.user
            comment.resume = Resume.objects.get(
                pk=request.POST.get('last_resume_pk'))
            comment.save()
            messages.success(request, 'comment added')
        form = ResumeCommentForm()
        return self.render_to_response({
            'view': self,
            'form': form,
            'resume_ctx': self.get_resume_ctx(self.student),

        })


class ResumeStudentTopView(SidebarMixin, TemplateView):
    template_name = 'resume/student_top.html'
    section_title = 'Resume Comments'

    def get_resume_ctx(self, user):
        ctx = ResumeCtx()
        for resume in user.resumes.all():
            if resume.desc not in ctx.jobs:
                job = ResumeCtxJob()
                job.desc = resume.desc
                ctx.jobs[resume.desc] = len(ctx.ordered_jobs)
                ctx.ordered_jobs.append(job)
            # get the job object
            job = ctx.ordered_jobs[ctx.jobs[resume.desc]]
            # create a new version for this job
            version = ResumeCtxVersion()
            version.last_updated_time = resume.created_date
            version.url = resume.file.url
            version.pk = resume.pk
            # get all comments for that version
            for comment in resume.comments.all():
                author_id = comment.commenter.username
                author_fullname = comment.commenter.last_name + ' ' + comment.commenter.first_name
                cmt = ResumeCtxComment(
                    comment.text, author_id, author_fullname, comment.created_date)
                version.comments.append(cmt)
            job.versions.append(version)
        ctx.display_order()
        return ctx

    def get(self, request):
        return self.render_to_response({
            'view': self,
            'comment_form': ResumeCommentForm(),
            'resume_form': ResumeCreateForm(),
            'resume_ctx': self.get_resume_ctx(request.user)
        })

    def post(self, request):
        if 'update_resume' in request.POST:
            if 'resume' in request.FILES:
                resume = Resume.objects.create(
                    user=request.user, desc=request.POST['desc'],
                    file=request.FILES['resume'])
                resume.save()
                messages.success(request, 'resume updated')
            else:
                messages.error(request, 'please add a new file')
        elif 'create_resume' in request.POST:
            resume_form = ResumeCreateForm(request.POST, request.FILES)
            if resume_form.is_valid():
                resume = resume_form.save(commit=False)
                resume.user = request.user
                resume.save()
                messages.success(request, 'resume created')
        else:
            form = ResumeCommentForm(request.POST)
            if form.is_valid():
                comment = form.save(commit=False)
                comment.commenter = request.user
                comment.resume = Resume.objects.get(
                    pk=request.POST.get('last_resume_pk'))
                comment.save()
                messages.success(request, 'comment added')

        return self.render_to_response({
            'view': self,
            'comment_form': ResumeCommentForm(),
            'resume_form': ResumeCreateForm(),
            'resume_ctx': self.get_resume_ctx(request.user)
        })


class ResumeClassView(
        UserCourseRelatedMixin, SidebarMixin,
        ListView, PageinatorMixin):

    course = None
    section_title = 'Manage Class Resume Reviews'
    taskselect = None
    template_name = 'resume/class_view.html'
    context_object_name = 'user_list'

    @property
    def search_url(self):
        return 'resume:class_view'

    @property
    def search_url_para(self):
        return self.course.id

    def __init__(self, **kwargs):
        super(ResumeClassView, self).__init__(**kwargs)

    def dispatch(self, request, pk):
        self.course = get_object_or_404(Course, id=pk)
        self.course_id = pk
        self.taskselect = SelectAssigneeForm()
        return super(ResumeClassView, self).dispatch(request, pk)

    def get_queryset(self):
        queryset = self.course.students.all()
        queryset = super(ResumeClassView, self).filter_queryset(
            queryset)
        return queryset

    def render_to_response(self, context, **response_kwargs):
        return super(ResumeClassView, self).render_to_response(
            context, **response_kwargs
        )

    def get_context_data(self, **kwargs):
        context = super(ResumeClassView, self).get_context_data(**kwargs)

        q = self.request.GET.get('q')
        if q:
            context['q'] = q

        return context
